import hashlib
import json
from django import forms
import time
from com.kjssoft.rainbow import LOGGER
from com.kjssoft.rainbow.album.models import RainbowPhotoFrameAlbum
from com.kjssoft.rainbow.consts import PhotoFrameConsts
from com.kjssoft.rainbow.frame.models import RainbowPhotoFrame, RainbowPhotoFrameCell, RainbowPhotoFrameComment
from com.kjssoft.rainbow.image.models import RainbowImage
from com.kjssoft.rainbow.label.models import RainbowPhotoFrameLabel

__author__ = 'Sea'

class RainbowPhotoFrameForm(forms.ModelForm):

    PHOTO_COMMENT_SPLIT = "!~~::--split--::~~!"

    photos   = forms.CharField()
    labels   = forms.CharField(required=False)
    status   = forms.IntegerField(widget=forms.Select(
        choices = (
            (PhotoFrameConsts.Status.DRAFT, 'DRAFT'),
            (PhotoFrameConsts.Status.VERIFYING, 'VERIFYING'),
        )
    ))

    def __init__(self, user = None, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=None, label_suffix=':', empty_permitted=False, instance=None):
        super(RainbowPhotoFrameForm, self).__init__(data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted, instance)
        self.user = user

    def clean_photos(self):
        photos = self.cleaned_data.get('photos')
        photos = json.loads(photos)
        photo_frame_cell_model_list = []
        for photo in photos:
            LOGGER.debug(photo)
            photo_image_id = photo[0]
            photo_comment = photo[1]
            photo_create_ms = photo[2]
            LOGGER.debug('photo %s comment %s create at %s' % (
                photo_image_id,
                photo_comment,
                photo_create_ms
            ))
            try:
                photo_frame_cell_model = RainbowPhotoFrameCell.objects.create(
                    image = RainbowImage.objects.get(id = int(photo_image_id)),
                    create_ms = int(photo_create_ms / 1000)
                )
                if photo_comment:
                    photo_frame_comment = RainbowPhotoFrameComment.objects.create(
                        comment = photo_comment,
                        commentator = self.user,
                        publish_ms = int(time.time())
                    )
                    photo_frame_cell_model.comment = photo_frame_comment
                photo_frame_cell_model_list.append(photo_frame_cell_model)
            except RainbowImage.DoesNotExist as e:
                LOGGER.error(e)
        LOGGER.debug('photos %s' % photos)
        md5 = hashlib.md5()
        for photo_instance in photo_frame_cell_model_list:
            md5.update(photo_instance.image.uuid)
        md5.update(str(self.user.username))
        self.instance.md5 = md5.hexdigest()
        return photo_frame_cell_model_list

    def clean_labels(self):
        labels = self.cleaned_data.get('labels')
        label_model_list = []
        if labels:
            labels = json.loads(labels)
            for label in labels:
                label_models = RainbowPhotoFrameLabel.objects.filter(keyword = label)
                if label_models.count():
                    label_model = label_models[0]
                else:
                    label_model = None
                    if label:
                        label_model = RainbowPhotoFrameLabel.objects.create(
                            keyword = label
                        )
                        label_model.save()
                if label_model:
                    label_model_list.append(label_model)
        return label_model_list

    def clean_status(self):
        status = self.cleaned_data.get('status')
        self.instance.status = status
        return status

    def clean_album(self):
        album = self.cleaned_data.get('album')
        LOGGER.debug('album %s' % album)
        if not album:
            try:
                album = RainbowPhotoFrameAlbum.objects.get(name='default', user=self.user)
            except RainbowPhotoFrameAlbum.DoesNotExist as e:
                album = RainbowPhotoFrameAlbum.objects.create(
                    user = self.user,
                    name = 'default',
                    create_ms = int(time.time()),
                    status = 1
                )
                album.save()
        return album

    def clean(self):
        self.instance.user = self.user
        self.instance.publish_ms = int(time.time())
        return super(RainbowPhotoFrameForm, self).clean()

    class Meta:
        model = RainbowPhotoFrame
        fields = (
            'album',
            'subject',
            'description',
            'layout',
            'scope',
        )

class RainbowPhotoAddCommentForm(forms.ModelForm):

    class Meta:
        model = RainbowPhotoFrameComment
        fields = (
            'comment',
        )
